<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\VerificationCodeRequest;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use Overtrue\EasySms\EasySms;

class VerificationCodesController extends Controller {
    public function store(VerificationCodeRequest $request,EasySms $easySms){
        $captchaKey = 'cc_'.$request->captcha_key;
        $captchaData = Cache::get($captchaKey);
        if(!$captchaData) abort(403,'图形验证码获取失败');
        if(!hash_equals($captchaData['code'],$request->captcha_code)){
            Cache::forget($captchaKey);
            throw new AuthenticationException('验证码输入错误');
        }

        $phone = $captchaData['phone'];
        if(!app()->environment('production')){
            $code = '8888';
        }else{
            $code = str_pad(random_int(1,9999),4,0,STR_PAD_LEFT);
            try {
                $easySms->send($phone, [
                    'template' => config('easysms.gateways.aliyun.templates.register'),
                    'data' => [
                        'code' => $code
                    ],
                ]);
            } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
                $message = $exception->getException('aliyun')->getMessage();
                abort(500,$message ?: '手机验证码发送失败');
            }
        }

        //缓存的key
        $key = Str::random(15);
        $cacheKey = 'vc_'.$key;
        $expireAt = now()->addMinutes(5);
        Cache::put($cacheKey,compact('phone','code'),$expireAt);
        //返回json
        return response()->json([
            'key'=>$key,
            'expireAt'=>$expireAt->toDateTimeString()
        ])->setStatusCode(201);
    }
}
